package com.example.bitintershipbbs.controller;

import com.alibaba.fastjson.JSON;
import com.example.bitintershipbbs.DTO.Msg;
import com.example.bitintershipbbs.mapper.UserMapper;
import com.example.bitintershipbbs.model.User;
import com.google.inject.spi.Message;
import okhttp3.Request;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sun.applet.resources.MsgAppletViewer_sv;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@CrossOrigin
@Controller
public class AuthorizeController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/signup")
    public ResponseEntity<Msg> signUp(@RequestParam("email") String email,
                                      @RequestParam("username") String username,
                                      @RequestParam("password") String password,
                                      HttpServletResponse response,
                                      HttpServletRequest request){

        Msg msg = new Msg();
        System.out.println("sign up");
        if(userMapper.findByEmail(email) != null){
            msg.setCode(400);
            msg.setMessage("邮箱已注册！");
            System.out.println(msg);
            System.out.println(msg);
            return ResponseEntity.status(400).body(msg);
        }
        if (userMapper.findByUsername(username) != null){
            msg.setCode(400);
            msg.setMessage("用户名"+username+"已经存在");
            System.out.println(msg);
            System.out.println(msg);
            return ResponseEntity.status(400).body(msg);
        }

        String token = UUID.randomUUID().toString();
        User user = new User();
        user.setEmail(email);
        user.setName(username);
        user.setPsw(password);
        user.setToken(token);
        user.setGmt_create(System.currentTimeMillis());
        user.setGmt_modified(user.getGmt_create());
        user.setToken(token);
        userMapper.createUser(user);

        response.addCookie(new Cookie("token", token));
        request.getSession().setAttribute("user", user);

        msg.setCode(200);
        msg.setMessage("用户注册成功");
        System.out.println(user);
        return ResponseEntity.status(200).body(msg);
    }

    @PostMapping("/login")
    public ResponseEntity<Object> login(@Param("email") String email,
                        @Param("password") String password,
                        HttpServletRequest request,
                        HttpServletResponse response){
        User user = (User) request.getSession().getAttribute("user");
        System.out.println("login");
        if(user != null){
            System.out.println(user);
            return ResponseEntity.status(200).body(user);
        }
        else {
            Cookie[]cookies = request.getCookies();
            if(cookies != null && cookies.length > 0){
                for (Cookie cookie: cookies) {
                    if(cookie.getName().equals("token")){
                        String token = cookie.getValue();
                        user = userMapper.findByToken(token);
                        if (user != null) {
                            request.getSession().setAttribute("user", user);
//                        System.out.println(request.getSession().getAttribute("user"));
                            System.out.println(user);
                            return ResponseEntity.status(200).body(user);
                        }
                    }
                }
            }
        }

        Msg msg = new Msg();
        user = userMapper.findByEmail(email);
        if (user == null || !user.getPsw().equals(password)) {
            msg.setCode(400);
            msg.setMessage("邮箱或密码错误");
            System.out.println(msg);
            return ResponseEntity.status(400).body(msg);
        }else{
            response.addCookie(new Cookie("token", user.getToken()));
            request.getSession().setAttribute("user", user);
            System.out.println(user);
            return ResponseEntity.status(200).body(user);
        }
    }

    @GetMapping("/imformation")
    public ResponseEntity<Object> getInformation(@Param("id") Integer id,
                                                 HttpServletRequest request,
                                                 HttpServletResponse response){
        User user = new User();
        user = (User) request.getSession().getAttribute("user");
        System.out.println("get information");
        if (user != null) {
            System.out.println(user);
            return ResponseEntity.status(200).body(user);
        }
        else {
//            Cookie[] cookies = request.getCookies();
//            if (cookies != null) {
//                for (Cookie cookie: cookies) {
//                    if (cookie.getName().equals("token")) {
//                        String token = cookie.getValue();
//                        user = userMapper.findByToken(token);
//                        if (user != null) {
//                            System.out.println(user);
//                            return ResponseEntity.status(200).body(user);
//                        }
//                    }
//                }
//            }
            if(id != null){
                user = userMapper.findById(id);
                if (user != null) {
                    System.out.println(user);
                    return ResponseEntity.status(200).body(user);
                }
            }
        }
        Msg msg = new Msg();
        msg.setCode(400);
        msg.setMessage("用户未登录");
        System.out.println(msg);
        return ResponseEntity.status(400).body(msg);
    }

    @GetMapping("/logout")
    private ResponseEntity<Object> logout(HttpServletRequest request, HttpServletResponse response){
        System.out.println("log out");
        request.getSession().removeAttribute("user");
        request.getSession().invalidate();

        Cookie cookie = new Cookie("token",null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);

        Msg msg = new Msg();
        msg.setCode(200);
        msg.setMessage("退出登录成功");
        System.out.println(msg);
        return ResponseEntity.status(200).body(msg);
    }
}
